using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SoftManager
{
    public partial class Form1 : Form
    {
        // 系统托盘图标
        private NotifyIcon trayIcon;
        private ContextMenuStrip trayMenu;
        // USB存储设备控制器
        private UsbStorageController usbController;
        public string currentVersion = "1.0.3";
        public Form1()
        {
            // 初始化USB存储设备控制器
            usbController = new UsbStorageController();

            if (!usbController.IsAdministrator())
            {
                //MessageBox.Show("此程序需要管理员权限。\n程序将自动重启并请求权限。",
                //"权限请求", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //usbController.RestartAsAdministrator();
            }
            InitializeComponent();
            InitializeTrayIcon();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                // 设置窗体启动时最小化且不显示在任务栏
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                this.Hide(); // 隐藏窗体



                // 启动时异步调用初始化任务
                Thread initThread = new Thread(ExecuteInitializationTasks);
                initThread.IsBackground = true;
                initThread.Start();
            }
            catch (Exception ex)
            {
                // 不显示错误信息，静默处理
                Console.WriteLine("初始化失败: " + ex.Message);
            }
        }

        ///// <summary>
        ///// 执行初始化任务
        ///// </summary>
        //private void ExecuteInitializationTasks()
        //{
        //    try
        //    {
        //        // 这里可以添加需要在启动时执行的初始化任务
        //        // 例如：获取系统信息、初始化配置等
        //        Console.WriteLine("正在执行初始化任务...");

        //        // 模拟一些初始化工作
        //        Thread.Sleep(1000);

        //        Console.WriteLine("初始化任务完成");
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"初始化任务执行失败: {ex.Message}");
        //    }
        //}

        /// <summary>
        /// 初始化系统托盘图标
        /// </summary>
        private void InitializeTrayIcon()
        {
            // 创建右键菜单
            trayMenu = new ContextMenuStrip();
            trayMenu.Items.Add("显示主窗口", null, ShowMainWindow);
            trayMenu.Items.Add("-");
            trayMenu.Items.Add("检查更新", null, CheckUpdateFromTray);
            trayMenu.Items.Add("-");
            trayMenu.Items.Add("退出", null, ExitApplication);

            // 创建系统托盘图标
            trayIcon = new NotifyIcon()
            {
                Icon = SystemIcons.Application,
                ContextMenuStrip = trayMenu,
                Visible = true,
                Text = "柳州市妇幼保健院 信息系统"
            };

            // 双击托盘图标显示主窗口
            trayIcon.DoubleClick += (s, e) => ShowMainWindow(s, e);
        }

        /// <summary>
        /// 显示主窗口
        /// </summary>
        private void ShowMainWindow(object sender, EventArgs e)
        {
            // 确保窗口可见
            this.ShowInTaskbar = true;

            // 先显示窗口，再设置窗口状态
            this.Show();

            // 设置窗口状态为正常
            this.WindowState = FormWindowState.Normal;

            // 激活窗口并置于前台
            this.Activate();
            this.BringToFront();

            // 确保窗口获得焦点
            this.Focus();
        }

        /// <summary>
        /// 从系统托盘检查更新
        /// </summary>
        private void CheckUpdateFromTray(object sender, EventArgs e)
        {
            AutoCheckUpdate();
        }

        

        

        /// <summary>
        /// 退出应用程序
        /// </summary>
        private void ExitApplication(object sender, EventArgs e)
        {
            trayIcon.Visible = false;
            Application.Exit();
        }

        /// <summary>
        /// 自动检查更新
        /// </summary>
        private void AutoCheckUpdate()
        {
            try
            {
                // 获取当前版本
                string _currentVersion = currentVersion;

                // 创建自动更新帮助类实例
                string updateUrl = "http://10.3.255.92:16335";
                AutoUpdateHelper updateHelper = new AutoUpdateHelper(updateUrl, "SoftManager", _currentVersion, this);

                // 检查更新，如果有更新则自动执行更新
                updateHelper.CheckUpdateAndAutoInstall();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"自动检查更新失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 显示本机MAC地址二维码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_display_qrcode_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取本机MAC地址
                string macAddress = GetLocalMacAddress();

                if (!string.IsNullOrEmpty(macAddress) && macAddress != "获取失败")
                {
                    // 生成二维码
                    Bitmap qrCodeBitmap = QrCodeHelper.GenerateQrCode(macAddress);

                    // 创建新窗口显示二维码
                    Form qrForm = new Form()
                    {
                        Text = "本机MAC地址二维码",
                        Size = new Size(400, 450),
                        StartPosition = FormStartPosition.CenterParent,
                        FormBorderStyle = FormBorderStyle.FixedDialog,
                        MaximizeBox = false,
                        MinimizeBox = false
                    };

                    // 创建PictureBox显示二维码
                    PictureBox picQrCode = new PictureBox()
                    {
                        Image = qrCodeBitmap,
                        SizeMode = PictureBoxSizeMode.CenterImage,
                        Size = new Size(300, 300),
                        Location = new Point(50, 20)
                    };

                    // 创建标签显示MAC地址文本
                    Label lblMacAddress = new Label()
                    {
                        Text = "MAC地址: " + macAddress,
                        Font = new Font("宋体", 12, FontStyle.Bold),
                        AutoSize = true,
                        Location = new Point(50, 330),
                        ForeColor = Color.Blue
                    };

                    // 创建关闭按钮
                    Button btnClose = new Button()
                    {
                        Text = "关闭",
                        Size = new Size(80, 30),
                        Location = new Point(160, 360),
                        DialogResult = DialogResult.OK
                    };

                    // 添加控件到窗口
                    qrForm.Controls.Add(picQrCode);
                    qrForm.Controls.Add(lblMacAddress);
                    qrForm.Controls.Add(btnClose);

                    // 显示窗口
                    qrForm.ShowDialog(this);
                }
                else
                {
                    MessageBox.Show("无法获取本机MAC地址！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成MAC地址二维码失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取本机MAC地址
        /// </summary>
        /// <returns>MAC地址字符串，格式如"8C:32:23:3A:AC:71"</returns>
        private string GetLocalMacAddress()
        {
            try
            {
                foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (nic.OperationalStatus == OperationalStatus.Up &&
                        nic.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
                        nic.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
                    {
                        var macBytes = nic.GetPhysicalAddress().GetAddressBytes();
                        if (macBytes.Length > 0)
                        {
                            return string.Join(":", macBytes.Select(b => b.ToString("X2")));
                        }
                    }
                }
                return "获取失败";
            }
            catch
            {
                return "获取失败";
            }
        }

        /// <summary>
        /// 检查更新按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_check_update_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前版本（实际项目中可以从配置文件或程序集信息中获取）
                string _currentVersion = currentVersion;

                // 创建自动更新帮助类实例
                // 使用实际的更新服务器地址
                string updateUrl = "http://10.3.255.92:16335";
                AutoUpdateHelper updateHelper = new AutoUpdateHelper(updateUrl, "SoftManager", _currentVersion, this);

                // 检查更新
                updateHelper.CheckUpdate();
            }
            catch (Exception ex)
            {
                MessageBox.Show("检查更新失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 窗体关闭事件，最小化到系统托盘而不是退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 如果是用户关闭窗口，则取消关闭事件并最小化到系统托盘
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
                this.ShowInTaskbar = false;
            }
            else
            {
                // 如果是系统关闭或其他原因，则正常退出
                if (trayIcon != null)
                {
                    trayIcon.Visible = false;
                    trayIcon.Dispose();
                }
            }
        }

        /// <summary>
        /// 处理注册表键，提取软件信息
        /// </summary>
        /// <param name="registryKey">注册表键路径</param>
        /// <param name="softwareList">软件列表</param>
        /// <param name="source">数据源</param>
        private void ProcessRegistryKey(string registryKey, List<object> softwareList, string source)
        {
            using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey))
            {
                if (key != null)
                {
                    foreach (string subkeyName in key.GetSubKeyNames())
                    {
                        try
                        {
                            using (RegistryKey subkey = key.OpenSubKey(subkeyName))
                            {
                                if (subkey != null)
                                {
                                    string displayName = subkey.GetValue("DisplayName") as string;
                                    if (!string.IsNullOrEmpty(displayName))
                                    {
                                        string displayVersion = subkey.GetValue("DisplayVersion") as string ?? "";
                                        string publisher = subkey.GetValue("Publisher") as string ?? "";
                                        string installDate = subkey.GetValue("InstallDate") as string ?? "";
                                        string installLocation = subkey.GetValue("InstallLocation") as string ?? "";

                                        // 格式化安装日期
                                        if (!string.IsNullOrEmpty(installDate) && installDate.Length == 8)
                                        {
                                            installDate = $"{installDate.Substring(0, 4)}-{installDate.Substring(4, 2)}-{installDate.Substring(6, 2)}";
                                        }

                                        var softwareInfo = new
                                        {
                                            Name = displayName,
                                            Version = displayVersion,
                                            Publisher = publisher,
                                            InstallDate = installDate,
                                            InstallLocation = installLocation,
                                            Source = source
                                        };
                                        softwareList.Add(softwareInfo);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"处理注册表项 {subkeyName} 时发生错误: {ex.Message}");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取已安装软件列表并保存为JSON文件
        /// </summary>
        private string GetInstalledSoftware()
        {
            try
            {
                // 获取系统信息
                string hostName = Dns.GetHostName();
                string ipAddress = "";
                IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
                foreach (IPAddress ip in hostEntry.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ipAddress = ip.ToString();
                        break;
                    }
                }

                // 获取MAC地址
                string macAddress = "";
                foreach (var nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && nic.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback)
                    {
                        macAddress = nic.GetPhysicalAddress().ToString();
                        // 格式化MAC地址为XX:XX:XX:XX:XX:XX格式
                        if (macAddress.Length == 12)
                        {
                            macAddress = macAddress.Insert(2, ":").Insert(5, ":").Insert(8, ":").Insert(11, ":").Insert(14, ":");
                        }
                        break;
                    }
                }

                // 检查管理员权限
                bool hasAdminRights = usbController != null && usbController.IsAdministrator();

                // 创建软件列表
                List<object> softwareList = new List<object>();

                // 从注册表中获取已安装软件信息
                ProcessRegistryKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", softwareList, "Registry-32bit");

                // 64位软件的注册表位置
                ProcessRegistryKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", softwareList, "Registry-64bit");

                // 创建JSON数据
                var jsonData = new
                {
                    CollectionTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    ComputerName = Environment.MachineName,
                    HasAdminRights = hasAdminRights,
                    IPAddress = ipAddress,
                    MACAddress = macAddress,
                    SoftwareList = softwareList,
                    TotalCount = softwareList.Count,
                    Message = "成功获取软件列表"
                };

                // 转换为JSON字符串
                string jsonOutput = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData, Newtonsoft.Json.Formatting.Indented);
                return jsonOutput;
                //// 确保目录存在
                //string outputDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SoftwareReports");
                //if (!Directory.Exists(outputDir))
                //{
                //    Directory.CreateDirectory(outputDir);
                //}

                //// 写入文件
                //string outputFile = Path.Combine(outputDir, $"InstalledSoftware_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.json");
                //File.WriteAllText(outputFile, jsonOutput);

                //Console.WriteLine($"已成功保存软件列表到文件: {outputFile}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取已安装软件列表时发生错误: {ex.Message}");
                return "error";
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="paramData"></param>
        /// <param name="headerDic"></param>
        /// <param name="Method"></param>
        /// <returns></returns>
        public static string HttpPostJson(string Url, string paramData, Dictionary<string, string> headerDic = null, string Method = "POST")
        {
            string jsons;
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(Url);
                wbRequest.KeepAlive = false;
                wbRequest.Method = Method;
                wbRequest.ContentType = "application/json";
                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        jsons = sread.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "服务连接");
                return $"ex:{ex.Message}";
            }
            return jsons;
        }

        private void ExecuteInitializationTasks()
        {
            // 创建获取已安装软件列表的线程
            Thread softwareThread = new Thread(() =>
            {
                try
                {
                    // 获取已安装软件列表并保存为JSON文件
                    string _url = $"https://www.lzetyy.com:8022/SoftwareInfo/SubmitSoftwareInfo";
                    string _softListJson = GetInstalledSoftware();
                    if (_softListJson != "error")
                    {
                        HttpPostJson(_url, _softListJson);
                    }
                    //Console.WriteLine("已成功获取并保存已安装软件列表");
                }
                catch (Exception ex)
                {
                    //Console.WriteLine($"获取已安装软件列表失败: {ex.Message}");
                    throw ex;
                }
            });
            softwareThread.IsBackground = true;
            softwareThread.Start();
        }
    }
}
